package com.wawu.server.dao;

import com.wawu.common.annotation.IOC.component.Repository;
import com.wawu.common.exception.BaseException;
import com.wawu.common.utils.SQLBuilder.SelectSQLBuilder;
import com.wawu.common.utils.SQLBuilder.UpdateSQLBuilder;
import com.wawu.common.utils.SQLExcutorUtil;
import com.wawu.pojo.entity.Order;
import com.wawu.pojo.query.OrderQuery;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Repository
public class OrdersDAO {
    /**
     * 动态条件查询订单
     * @param orderQuery
     * @return
     */
    public List<Order> getOrders(OrderQuery orderQuery) throws SQLException {
        SelectSQLBuilder selectSqlBuilder = new SelectSQLBuilder("orders")
                .addDynamicCondition("id","=",orderQuery.getId())
                .addDynamicCondition("userId", "=", orderQuery.getUserId())
                .addDynamicCondition("state", "=", orderQuery.getState())
                .addBetweenCondition("updatetime",orderQuery.getStartDate(),orderQuery.getEndDate())
                .addBetweenCondition("amount",orderQuery.getMinAmount(),orderQuery.getMaxAmount())
                .addOrderBy("updatetime","DESC");
        return SQLExcutorUtil.queryList(selectSqlBuilder.getSQL(), Order.class, selectSqlBuilder.getParams());
    }

    /**
     * 根据 id 更新订单（GPT完成，不管了）
     * @param order 订单对象，包含需要更新的字段
     */
    public void update(Order order) {
        if (order.getId() == null) {
            throw new BaseException("订单 ID 为空，无法更新");
        }

        // 构建 UpdateSQLBuilder
        UpdateSQLBuilder updateSQLBuilder = new UpdateSQLBuilder("orders")
                .setField("state", order.getState())
                .setField("goodsNum", order.getGoodsNum())
                .setField("amount", order.getAmount())
                .addDynamicCondition("id", "=", order.getId());//TODO 待优化：此处也是不是动态条件

        try {
            // 调用 SQLExcutorUtil 的 update 方法执行更新
            int rowsAffected = SQLExcutorUtil.update(updateSQLBuilder.getSQL(), updateSQLBuilder.getParams());
            if (rowsAffected == 0) {
                throw new BaseException("更新失败，未找到对应的记录");
            }
        } catch (SQLException e) {
            throw new BaseException("数据库更新操作失败"+e);
        }
    }


    /**
     * 购物功能，创建新订单
     */
    public void insert(Order order) throws SQLException {
        String sql = "insert into orders (userId,goodsDetailId,goodsNum,amount,state,updatetime,createtime) values(?,?,?,?,?,?,?)";
        ArrayList<Object> params = new ArrayList<>();
        params.add(order.getUserId());
        params.add(order.getGoodsDetailId());
        params.add(order.getGoodsNum());
        params.add(order.getAmount());
        params.add(order.getState());
        params.add(order.getUpdateTime());
        params.add(order.getCreateTime());

        int rowsAffected = SQLExcutorUtil.update(sql,params.toArray());
        if (rowsAffected == 0) {
            throw new BaseException("插入失败");
        }

    }

    /**
     * 根据订单id删除订单
     * @param orderId
     */
    public void deleteById(Long orderId) throws SQLException {
        String sql="DELETE FROM orders WHERE id=?";
        SQLExcutorUtil.update(sql,orderId);
    }

}
